﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pTools.cMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace pTools.ChildWin
{
    public partial class PrintWHD : Form
    {
        string datas = "";
        DBHelper db;
        HttpAgreement http;
        public PrintWHD(string  par)
        {
            InitializeComponent();
            datas = par;
            db = new DBHelper();
            http = new HttpAgreement();
        }

        private void PrintWHD_Load(object sender, EventArgs e)
        {
            try
            {
                loadPrintTemplte();
                loadPrint();
                ShowData();
                loadPrintBar(dhdCode);
                tbNumber.Text = "1";
                tbRePrint.Text = "1";
                this.Text = "外购到货单打印";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        string dhdCode = "",wareHouse="",tssx="";
        double o_mNum = 0,o_cNum=0;
        private void ShowData()
        {
            var json = JsonConvert.DeserializeObject<JObject>(datas);
            tbDanHao.Text = json["cCode"].ToString();
            tbProCode.Text = json["cInvCode"].ToString();
            tbProName.Text = json["cInvName"].ToString();
            tbSpec.Text = json["cInvStd"].ToString();
            tbGongFang.Text = json["cVenName"].ToString();
            lbMUnit.Text = json["mUnitName"].ToString();
            lbCUnit.Text = json["cUnitName"].ToString();
            tbWarehouse.Text = json["cWhName"].ToString();
            wareHouse = json["cWhCode"].ToString();
            if(!string.IsNullOrWhiteSpace(json["iNum"].ToString()))
            {
                o_cNum = double.Parse(json["iNum"].ToString());
            }
            if (!string.IsNullOrWhiteSpace(json["iQuantity"].ToString()))
            {
                o_mNum = double.Parse(json["iQuantity"].ToString());
            }
            tssx = json["tssx"].ToString();
            tbDanHao.ReadOnly = true;
            tbProCode.ReadOnly = true;
            tbProName.ReadOnly = true;
            tbSpec.ReadOnly = true;
            tbGongFang.ReadOnly = true;
            tbWarehouse.ReadOnly = true;
            dhdCode = json["cCode"].ToString();
            warePosition(wareHouse);
        }
        private void warePosition(string wareCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select isnull(c_huowei,'') huowei from fun_WareHouse_Info where houseCode='"+ wareCode +"'");
            var table = db.getData(sb.ToString(),"");
            DataTable ptable = new DataTable();
            ptable.Columns.Add("pcode");
            ptable.Columns.Add("pname");
            if (table.Rows.Count > 0)
            {
                if (!string.IsNullOrWhiteSpace(table.Rows[0][0].ToString()))
                {
                    var list = JsonConvert.DeserializeObject<List<JObject>>(table.Rows[0][0].ToString());
                    foreach (var obj in list)
                    {
                        DataRow r = ptable.NewRow();
                        r["pcode"] = string.Format("{0}({1})", obj["name"].ToString(), obj["value"].ToString());
                        r["pname"] = string.Format("{0}({1})", obj["name"].ToString(), obj["value"].ToString());
                        ptable.Rows.Add(r);
                    }
                }
            }
            cbPosition.DataSource = ptable;
            cbPosition.ValueMember = "pcode";
            cbPosition.DisplayMember = "pname";
        }
        /// <summary>
        /// 加载已打印条码的数值
        /// </summary>
        /// <param name="orderNum"></param>
        private void loadPrintBar(string orderNum)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from bar_ProductBarCode_info where status='Y'");
            sb.Append(" and U8relationCode='"+ orderNum +"' and proCode='"+tbProCode.Text.Trim()+"'");
            sb.Append(" and c_tssx='" + tssx + "' and barType='chengpin'");
            var table = db.getData(sb.ToString(),"");
            double mNum = 0,cNum=0;
            foreach (DataRow r in table.Rows)
            {
                mNum += double.Parse(r["c_gongjin"].ToString());
                cNum += double.Parse(r["c_mishu"].ToString());
            }
            tbInfo.Text = string.Format("已打印数：{0}，主计量数：{1}，辅计量数：{2}",table.Rows.Count,mNum,cNum);
            tbInfo.ReadOnly = true;
            if (o_mNum <= mNum && o_cNum <=cNum)
            {
                btnPrint.Enabled = false;
            }
        }
        /// <summary>
        /// 打印模板
        /// </summary>
        private void loadPrintTemplte()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select lbCode,lbName from bar_PrintTemplates_list where status=1");
            sb.Append(" and lType='wgrk'");
            var table = db.getData(sb.ToString(), "");
            cbTemplate.DataSource = table;
            cbTemplate.ValueMember = "lbCode";
            cbTemplate.DisplayMember = "lbName";
        }
        /// <summary>
        /// 打印机列表
        /// </summary>
        private void loadPrint()
        {
            PrintDocument print = new PrintDocument();
            string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
            {
                DataRow r = dt.NewRow();
                r["name"] = sPrint;
                r["value"] = sPrint;
                dt.Rows.Add(r);
            }
            cbPrint.DataSource = dt;
            cbPrint.ValueMember = "name";
            cbPrint.DisplayMember = "name";
            cbPrint.SelectedValue = sDefault;
        }

        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(tbMnum.Text))
                {
                    MessageBox.Show("主数量不允许为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrWhiteSpace(tbCnum.Text))
                {
                    MessageBox.Show("辅数量不允许为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                VisitService();
                loadPrintBar(dhdCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

      

   
        /// <summary>
        /// 打印接口访问
        /// </summary>
        private void VisitService()
        {

            Dictionary<string, string> barDic = new Dictionary<string, string>();
            barDic["machine"] = "";
            barDic["proCode"] = tbProCode.Text;
            barDic["proName"] = tbProName.Text;
            barDic["printNum"] = tbNumber.Text;
            barDic["gxCode"] = "WG";
            barDic["barStatus"] = "need-out";
            barDic["isInitial"] = "Y";
            barDic["wareHouse"] =wareHouse;
            barDic["planCode"] = "-";
            barDic["createuser"] = CommonMethods.userCode;
            barDic["proType"] = "";
            barDic["barType"] = "chengpin";
            barDic["unit"] = "Kg";
            barDic["number"] =tbMnum.Text;
            barDic["pUserCodes"] = CommonMethods.userPositionValue; ;//生产人员编码
            barDic["pusers"] = CommonMethods.userPositionTitle;//生产人员、岗位
            barDic["relationBar"] = CommonMethods.SinglePar;
            barDic["positionkey"] = CommonMethods.positionKey;
            barDic["thickness"] ="";
            barDic["width"] = "";
            barDic["c_mishu"] =tbCnum.Text;
            barDic["c_gongjin"] =tbMnum.Text;
            barDic["c_tssx"] = "";
            barDic["c_qupi"] = "";
            barDic["cu_outCompany"] = tbGongFang.Text ;
            barDic["memo"] = "外购";
            barDic["U8relationCode"] = tbDanHao.Text;
            barDic["proType"] = "WG";
            barDic["goodsPositionName"] =cbPosition.SelectedValue.ToString();
            var msg = http.PostJson("SaveBarCode", JsonConvert.SerializeObject(barDic));
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var json = JsonConvert.DeserializeObject<JObject>(msg);
                if (bool.Parse(json["Result"].ToString()))
                {
                    if (string.IsNullOrWhiteSpace(json["Data"].ToString()))
                    {
                        MessageBox.Show("接口返回数据异常，请联系开发人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    var bars = json["Data"].ToString().Split(',');
                    var table =CommonMethods.DHDPrintTable();
                    foreach (string s in bars)
                    {
         
                        #region 填充表格数据
                        var r = table.NewRow();
                        r["proName"] = tbProName.Text;
                        r["outCompany"] =tbGongFang.Text;
                        r["spec"] = tbSpec.Text;
                        r["proCode"] = tbProCode.Text;
                        r["mNum"] = string.Format("{0}({1})", tbMnum.Text,lbMUnit.Text);
                        r["cnum"] = string.Format("{0}({1})", tbCnum.Text, lbCUnit.Text); 
                        r["barCode"] = s;
                        r["orderCode"] = tbDanHao.Text;
                        r["date"] = DateTime.Now.ToString("yyyy-MM-dd");
                        r["userName"] = CommonMethods.userName;
                        table.Rows.Add(r);
                        #endregion
                      
                    }
                    if (table.Rows.Count > 0)
                    {
                        string info = "";
                        for (int i = 0; i < int.Parse(tbRePrint.Text); i++)
                        {
                            var pResult = CommonMethods.DoPrint(table, cbTemplate.Text, cbPrint.Text, ref info);
                            if (!pResult)
                            {
                                MessageBox.Show("条码打印失败：" + info, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                     
                    }
                 
                 

                }
                else
                {
                    MessageBox.Show(json["Message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("接口反馈异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
